// 请求接口工具类
const app = getApp();
var login = require('../utils/uctoo-login.js');
var host = require('../config.js').host;
var requestNum = 0;
var responseNum = 0;


/* 验证登陆的GET请求 */
function requestGet(url, params, successCallback, msg, failCallback) {
  let token = wx.getStorageSync('token');
  let openid = wx.getStorageSync('openid');
  let appid = wx.getStorageSync('appid');
  if (!token) { 
    wx.request({
            url: host + '/getTokenByOpenId',
            data: {
              openId: openid,
              userType: 3,
              ownerAppType: 1,
              wxAppId:appid
            },
            method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
            header: {
              'content-type': 'application/json'
            }, // 设置请求的 header
            success: function (res) {
              if (res.data.code == '200') {
                wx.setStorageSync('token', res.data.token)
                requestGet(url, params, successCallback, msg, failCallback);
              } else {
                wx.showToast({
                  title: res.data.msg,
                  icon: 'none'
                })
              }
            }
          });
  } else {
    wx.showLoading({
      title: msg ? msg : '加载中...',
      mask: true,
      success: function (req) {
        if (token) {
          // requestNum++;
          wx.request({
            // 此处加个 host 
            url: host + url,
            data: params,
            method: 'GET',
            header: {
              'Authorization': 'Bearer ' + token,
              'content-type': 'application/x-www-form-urlencoded',
              'X-Requested-With': 'XMLHttpRequest'
            },
            success: function (res) {
              wx.hideLoading();
              // responseNum++;
              if (res.header.SESSIONSTATUS == "TIMEOUT") {
                reLogin(() => {
                  request(url, params, successCallback, msg, failCallback);
                });
              } else {
                typeof successCallback == "function" && successCallback(res);
              }
            },
            fail: function (res) {
              wx.hideLoading();
              typeof failCallback == "function" && failCallback(res);
            }
          });
        } else {
          reLogin(() => {
            request(url, params, successCallback, msg, failCallback);
          });
        }
      }
    });
  }
}

/* 验证登陆的POST请求 */
function requestPost(url, params, successCallback, msg, failCallback) {
  let token = wx.getStorageSync('token');
  let openid = wx.getStorageSync('openid');
  if (!token) {
    wx.request({
            url: host + '/getTokenByOpenId',
            data: {
              openId: openid,
              userType: 3,
              ownerAppType: 1,
              wxAppId:appid
            },
            method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
            header: {
              'content-type': 'application/json'
            }, // 设置请求的 header
            success: function (res) {
              if (res.data.code == '200') {
                wx.setStorageSync('token', res.data.token)
              requestPost(url, params, successCallback, msg, failCallback);
              } else {
                wx.showToast({
                  title: res.data.msg,
                  icon: 'none'
                })
              }
            }
          });
    return;
  }
  wx.showLoading({
    title: msg ? msg : '加载中...',
    mask: true,
    success: function (req) {
      if (token) {
        // requestNum++;
        wx.request({
          url: host + url,
          data: params,
          method: 'POST',
          header: {
            'Authorization': 'Bearer ' + token,
            'content-type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
          },
          success: function (res) {
            wx.hideLoading();
            // responseNum++;
            if (res.header.SESSIONSTATUS == "TIMEOUT") {
              reLogin(() => {
                request(url, params, successCallback, msg, failCallback);
              });
            } else {
              typeof successCallback == "function" && successCallback(res);
            }
          },
          fail: function (res) {
            wx.hideLoading();
            typeof failCallback == "function" && failCallback(res);
          }
        });
      } else {
        reLogin(() => {
          request(url, params, successCallback, msg, failCallback);
        });
      }
    }
  });
}
/* 不验证登陆GET请求 */
function nonAuthRequestGet(url, params, successCallback, msg, failCallback) {
  // requestNum++
  wx.showLoading({
    title: msg ? msg : '加载中...',
    mask: true,
    success: function () {
      wx.request({
        url: host + url,
        data: params,
        method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
        // header: { 'content-type': 'application/x-www-form-urlencoded' }, // 设置请求的 header
        success: function (res) {
          wx.hideLoading();
          typeof successCallback == "function" && successCallback(res);
        },
        fail: function (res) {
          wx.hideLoading();
          typeof failCallback == "function" && failCallback(res);
        }
      });
    }
  });
}

/* 不验证登陆POST请求 */
function nonAuthRequestPost(url, params, successCallback, msg, failCallback) {
  // requestNum++
  wx.showLoading({
    title: msg ? msg : '加载中...',
    mask: true,
    success: function () {
      wx.request({
        url: host + url,
        data: params,
        method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
        // header: { 'content-type': 'application/x-www-form-urlencoded' }, // 设置请求的 header
        success: function (res) {
          wx.hideLoading();
          typeof successCallback == "function" && successCallback(res);
        },
        fail: function (res) {
          wx.hideLoading();
          typeof failCallback == "function" && failCallback(res);
        }
      });
    }
  });
}

function uploadFileLoading(url, filePath, successCallback, msg, failCallback) {
  let token = wx.getStorageSync('token');
  if (!app.globalData.sessionId && !token) {
    wx.showModal({
      title: '提示',
      content: '本操作需要登录',
      confirmText: '立即登录',
      cancelText: '暂不登录',
      success(res) {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/login/login',
          })
        } else {
          wx.switchTab({
            url: '/pages/index/index',
          })
        }
      }
    })
    return;
  }
  wx.showLoading({
    title: msg ? msg : '上传图片...',
    success: function () {
      if (token) {
        wx.uploadFile({
          url: host + url,
          filePath: filePath,
          name: 'file',
          header: {
            'Authorization': 'Bearer ' + token,
            // 'content-type': 'multipart/form-data',
            'X-Requested-With': 'XMLHttpRequest'
          },
          success: function (res) {
            wx.hideLoading();
            if (res.header && res.header.SESSIONSTATUS == "TIMEOUT") {
              reLogin(() => {
                uploadFileLoading(url, filePath, successCallback, msg, failCallback);
              });
            } else {
              typeof successCallback == "function" && successCallback(res);
            }
          },
          fail: function (res) {
            wx.hideLoading();
            typeof failCallback == "function" && failCallback(res);
          }
        })
      } else {
        reLogin(() => {
          uploadFileLoading(url, filePath, successCallback, msg, failCallback);
        });
      }
    }
  });
}

function validatePhone() {
  if (!app.globalData.phone) {
    wx.navigateTo({
      url: '../setPhone/setPhone',
    })
  }
}

function reLogin(callback) {
  let token = wx.getStorageSync('token');
  if (token) {
    wx.login({
      success: res => {
        reLogin2(token, res.code, callback);
      },
      fail: () => {
        wx.showModal({
          title: '提示',
          content: '本操作需要登录',
          confirmText: '立即登录',
          cancelText: '暂不登录',
          success(res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/login/login',
              })
            } else {
              wx.switchTab({
                url: '/pages/index/index',
              })
            }
          }
        })
      }
    })
  } else {
    wx.showModal({
      title: '提示',
      content: '本操作需要登录',
      confirmText: '立即登录',
      cancelText: '暂不登录',
      success(res) {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/login/login',
          })
        } else {
          wx.switchTab({
            url: '/pages/index/index',
          })
        }
      }
    })
  }
}

function reLogin2(token, code, callback) {
  wx.request({
    url: host + 'action/LoginAction/reLogin',
    data: {
      id: token,
      code: code
    },
    method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    }, // 设置请求的 header
    success: function (res) {
      if (res.data.state) {
        app.globalData['sessionId'] = res.data.sessionId;
        typeof callback == "function" && callback();
      } else {
        wx.showModal({
          title: '提示',
          content: '本操作需要登录',
          confirmText: '立即登录',
          cancelText: '暂不登录',
          success(res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/login/login',
              })
            } else {
              wx.switchTab({
                url: '/pages/index/index',
              })
            }
          }
        })
      }
    }
  });
}

module.exports = {
  requestPost: requestPost,
  requestGet: requestGet,
  nonAuthRequestGet: nonAuthRequestGet,
  nonAuthRequestPost: nonAuthRequestPost,
  uploadFileLoading: uploadFileLoading,
  validatePhone: validatePhone
}